<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/6
 * Time: 17:00
 */

namespace App\Models;


use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{

    protected $guarded = [];

    /**
     * @param $query
     * @return mixed
     * 普通分页
     */
    public function scopePages($query, $pageSize = 30)
    {
        $page = request()->input('page', 1);
        $pageSize = request()->input('pageSize', $pageSize);
        if ($page < 1) {
            $page = 1;
        }
        $offset = ($page - 1) * $pageSize;

        $data = [];
        $data['count'] = $query->count();
        $data['page'] = ceil($data['count'] / $pageSize);
        $data['data'] = $query->offset($offset)->limit($pageSize)->get();
        return $data;
    }

    /**
     * @param $query
     * @param $select
     * @return mixed
     * 带group分页
     */
    public function scopeGroupPages($query, $select = null)
    {
        $page = request()->input('page', 1);
        $pageSize = request()->input('pageSize', 30);
        if ($page < 1) {
            $page = 1;
        }
        $offset = ($page - 1) * $pageSize;
        $pages = clone $query;

        $data = [];
        $data['data'] = $query->offset($offset)->limit($pageSize)->get();
        if ($select) {
            $count = $pages->select(DB::raw('count(*) as count'), $select)->get();
        } else {
            $count = $pages->select(DB::raw('count(*) as count'))->get();
        }

        $data['count'] = count($count);
        $data['page'] = ceil($data['count'] / $pageSize);
        return $data;
    }

}